    package com.hsh.websocketdemo.config;

    import com.hsh.websocketdemo.handler.MyWebSocketHandler;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.server.ServerHttpRequest;
    import org.springframework.http.server.ServerHttpResponse;
    import org.springframework.web.socket.WebSocketHandler;
    import org.springframework.web.socket.config.annotation.EnableWebSocket;
    import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
    import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
    import org.springframework.web.socket.server.HandshakeInterceptor;

    import java.util.Map;

    /**
     * @author hsh
     * @date 2023/7/24 4:11
     */
    @Configuration //告诉SpringBoot这是一个配置类，让SpringBoot加载配置
    @EnableWebSocket //用于开启注解接收和发送消息
    public class WebSocketConfig implements WebSocketConfigurer {
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new MyWebSocketHandler(), "/ws")//设置处理类和连接路径
                    .setAllowedOrigins("*") //设置作用域
                    .addInterceptors(new MyWebSocketInterceptor());//设置拦截器
        }
        /**
         * 自定义拦截器拦截WebSocket请求
         */
        class MyWebSocketInterceptor implements HandshakeInterceptor {
            //前置拦截一般用来注册用户信息，绑定 WebSocketSession
            @Override
            public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                           WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
                System.out.println("前置拦截~~");
                String userName = "hsh";
                attributes.put("userName", userName);
                return true;
            }

            @Override
            public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                       WebSocketHandler wsHandler, Exception exception) {
                System.out.println("后置拦截~~");
            }
        }
    }